package br.embedded.socialapp.domain;

import java.util.Iterator;

import org.jgrapht.Graph;
import org.jgrapht.graph.SimpleGraph;


public class GraphBuilder
{
	private SimpleGraph<User, CustomEdge> graph;
	private String network;
	
	public GraphBuilder(String network)
	{
		this.graph = new SimpleGraph<User, CustomEdge>(CustomEdge.class);
		this.network = network;
	}
	
	public void add(User u1, User u2)
	{
		addVertex(u1);
		addVertex(u2);
		addEdge(u1, u2, getNetwork());
	}
	
	public void add(User u1, User u2, String socialNetwork)
	{
		addVertex(u1);
		addVertex(u2);
		addEdge(u1, u2, socialNetwork);
	}
	
	private void addVertex(User u)
	{
		if (!graph.containsVertex(u))
			graph.addVertex(u);
	}
	
	private void addEdge(User u1, User u2, String network)
	{
		CustomEdge c = getEdge(u1, u2);
		
		if (c == null)
		{
			CustomEdge customEdge = new CustomEdge();
			customEdge.addNetworkInfo(network);
			graph.addEdge(u1, u2, customEdge);
		}
		else
		{
			c.addNetworkInfo(network);
		}
	}
	
	public Graph<User, CustomEdge> getGraph()
	{
		return graph;
	}
	
	public String getNetwork()
	{
		return network;
	}
	
	private CustomEdge getEdge(User sourceVertex, User targetVertex)
    {
        if (graph.containsVertex(sourceVertex)
            && graph.containsVertex(targetVertex))
        {
            Iterator<CustomEdge> iter = graph.edgeSet().iterator();

            while (iter.hasNext()) {
                CustomEdge e = iter.next();

                boolean equalStraight =
                    sourceVertex.equals(graph.getEdgeSource(e))
                    && targetVertex.equals(graph.getEdgeTarget(e));

                boolean equalInverted =
                    sourceVertex.equals(graph.getEdgeTarget(e))
                    && targetVertex.equals(graph.getEdgeSource(e));

                if (equalStraight || equalInverted) {
                    return e;
                }
            }
        }

        return null;
    }
}
